import axios from 'axios';
import 'element-plus/theme-chalk/el-message.css';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import router from '@/router';

const http = axios.create({
  // 后端的基地址
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  // 接口超时时间
  timeout: 5000,
});

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const token = userStore.userInfo.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

http.interceptors.response.use(
  (response) => response.data,
  (error) => {
    // 统一错误提示
    ElMessage({
      type: 'warning',
      message: error.response.data.message,
    });
    // 401 token 错误处理
    // 清除本地数据
    // 跳转到登录页
    const userStore = useUserStore();
    if (error.response.status === 401) {
      userStore.clearUserInfo();
      router.push('/login');
    }
    Promise.reject(error);
  }
);

export default http;
